package com.example.project.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.IntentService;
import android.content.Intent;

public class MessageService extends IntentService{
	
	public MessageService() {
		super("Message Service");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String message = intent.getStringExtra("message");
		String address = intent.getStringExtra("address");
		String port = intent.getStringExtra("port");
		String token = intent.getStringExtra("token");
		String exam = intent.getStringExtra("exam");
		String uri = new StringBuffer("http://").append(address).append(':').append(port).append("/message").toString();

		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpPost httpPost = new HttpPost(uri);
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("token", token));
			nameValuePairs.add(new BasicNameValuePair("exam", exam));
			nameValuePairs.add(new BasicNameValuePair("content", message));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			httpClient.execute(httpPost, localContext);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

}
